package com.problem.leetcode;

/**
 * @author yangzhuoleo
 * @Description ${Description}
 * @create 2018-01-02 23:21
 **/
public class Problem8 {
    public static void main(String[] args) {

        System.out.println(myAtoi("1"));

    }

    public static int myAtoi(String str) {
        //1.越界
        //2.不是数字

        if (str.equals("")) {
            return 0;
        }
        str = str.trim();
        char[]  chars   = str.toCharArray();
        boolean reverse = chars[0] == '-' ? true : false;
        int     begin   = chars[0] == '-' || chars[0] == '+' ? 1 : 0;
        double    result  = 0;

        for (int index = begin; index < chars.length; ++index) {

            if (chars[index] < '0' || chars[index] > '9') {
                break;
            }

            result = (chars[index] - '0') + result * 10;
        }
        if (reverse) {
            result = -result;
        }

        if (result >= Integer.MAX_VALUE) {
            result = Integer.MAX_VALUE;
        }
        if (result <= Integer.MIN_VALUE) {
            result = Integer.MIN_VALUE;
        }

        return (int) result;

    }

}
